package com.list88zhu.android.sunflower.http;

import android.text.TextUtils;

import java.util.List;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * <pre><code>
 * 创建具体的retrofit
 *
 * Retrofit retrofit = new Retrofit.Builder()
 * client(clientBuilder.build())
 * baseUrl("https://news-at.zhihu.com")
 * addConverterFactory(GsonConverterFactory.create())
 * build();
 *  </code></pre>
 *
 * @author zhuyingming@qmtv.com
 * @date 2018/9/9
 */
public abstract class BaseConfig implements Api.Config {

    protected Api.ConfigParam configParams;

    @Override
    public void build(Retrofit.Builder builder, Api.ConfigParam configParams) {
        this.configParams = configParams;
        builder.client(getOkHttpClient());
        if(!TextUtils.isEmpty(getBaseUrl())) {
            builder.baseUrl(getBaseUrl());
        }else{
            builder.baseUrl(getBaseHttpUrl());
        }
        addConverterFactory(builder);
        addCallAdapterFactory(builder);
    }

    private void addConverterFactory(Retrofit.Builder builder) {
        List<Converter.Factory> factories = getConverterFactories();
        if(factories != null) {
            for(Converter.Factory factory : factories) {
                builder.addConverterFactory(factory);
            }
        }
    }

    private void addCallAdapterFactory(Retrofit.Builder builder) {
        List<CallAdapter.Factory> factories = getCallAdapterFactories();
        if(factories != null) {
            for(CallAdapter.Factory factory : factories) {
                builder.addCallAdapterFactory(factory);
            }
        }
    }

    protected String getBaseUrl() {
        return null;
    }

    protected HttpUrl getBaseHttpUrl() {
        return null;
    }

    protected abstract OkHttpClient getOkHttpClient();

    protected abstract List<Converter.Factory> getConverterFactories();

    protected abstract List<CallAdapter.Factory> getCallAdapterFactories();
}
